import requests
import json
from datetime import datetime
import os
##cron: 0 30 10 10,20,30 * ?
##new Env("中银立减金活动")
# 导入青龙通知模块
try:
    from notify import send
    HAS_NOTIFY = True
except ImportError:
    HAS_NOTIFY = False
    print("未找到青龙通知模块，将使用控制台输出")

# 通用请求头配置
COMMON_HEADERS = {
    "Host": "gd.brcloud.bankofchina.com",
    "Connection": "keep-alive",
    "charset": "utf-8",
    "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380243 MMWEBSDK/20221011 MMWEBID/9222 MicroMessenger/8.0.30.2260(0x28001E3B) WeChat/arm64 Weixin NetType/4G Language/zh_CN ABI/arm64 MiniProgramEnv/android",
    "content-type": "application/json",
    "Accept-Encoding": "gzip,compress,br,deflate",
    "Referer": "https://servicewechat.com/wxc1494f20537c4de6/69/page-frame.html"
}

# 从青龙环境变量获取authorization token
def get_authorization_token():
    """从环境变量获取token"""
    # 优先级1: 青龙环境变量 zy_token
    token = os.environ.get('zy_token')
    if token:
        print("从环境变量 zy_token 获取token成功")
        return token
    
    # 优先级2: 备用环境变量
    backup_vars = ['BOC_TOKEN', 'ZHONGYIN_TOKEN', 'TOKEN']
    for var_name in backup_vars:
        token = os.environ.get(var_name)
        if token:
            print(f"从环境变量 {var_name} 获取token成功")
            return token
    
    # 优先级3: 代码中的默认token（仅用于测试）
    default_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOjkyNjc1LCJzdWIiOiJMT0dJTiIsIm5iZiI6MTc2MTc1ODU1MiwidmFyIjoiNGxKajRjNXhZemFXUU92U2pkaDdNSmJRd0h0b0xWT0JVZ3FDL1FaeVZWR2l6OXdmZVN4SHE5NExUamllNnZCU2IzWUIvRThyMmdBZkVwZEFON3JwMWVZaXlCMzJlNmIzZUxVYk8veDNmNDlHb0l3L3JxOHoyTkx0MVM5S3grSmhySGtnOG9DQnBNOFI1bEozcnNmSDFSNFRDYzlSeVVEenZLRzgrTkg5cnBpQXJTWVY1L0sySDhESm04ak0yNWxrcnBkVElkR0Ryc2ROWGoxTWNtamJSeWp0V0lKbms2WkNBRDhUcnZxWDlEMTFrN1VmVzEzTHRxRzNSV1daOGJnbVJzVkUwZHhJWDJkVGdjZEgzMGMvVk9iMi9ZNkZROGgyZkRpUjNaNitLbitlbjNwQ0E1dlFjNHl1MGR2VjJkV1lFTi9IUDRVYVJHcU1BMFdFOG8vcUs0bnJSQ0NvK2FTV2JwRWZnNmUxc3BTeHFnb1FVNTNPUElIV1VrNEMzSFNFMHJzWFhmOC9NVkFmUTl3UHF4SkVGSUtBcTROblhKVVBheGtqZmxDckZCVT0iLCJpc3MiOiJ3eGMxNDk0ZjIwNTM3YzRkZTYiLCJleHAiOjE3NjE4MzA1NTIsImlhdCI6MTc2MTc1ODU1MiyianRpIjoiMTk4MzU4NTI1NDAyMTUzNzc5MiJ9.79drooeC9hwLg9IfJejbJO6IcizAWAlLVRrjvCjrtE4"
    
    # 检查默认token是否有效（不是占位符）
    if default_token and len(default_token) > 100 and "你的authorization_token" not in default_token:
        print("使用代码中的默认token")
        return default_token
    
    return None

# 初始化authorization token
AUTHORIZATION_TOKEN = get_authorization_token()

# 活动配置
ACTIVITIES = {
    "首绑礼遇": {
        "navi_id": 20,
        "description": "首次绑定银行卡到各平台"
    },
    "城市礼遇": {
        "navi_id": 23, 
        "description": "城市专属优惠活动"
    },
    "支付礼遇": {
        "navi_id": 6,
        "description": "支付相关优惠活动"
    }
}

# 通知标题
NOTIFY_TITLE = "中银立减金活动"

def check_token_validity(token):
    """检查token是否有效"""
    if not token:
        return False, "Token为空"
    
    if len(token) < 100:
        return False, "Token长度过短，可能无效"
    
    # 检查是否是占位符
    if "你的authorization_token" in token:
        return False, "请替换默认的占位符token"
    
    return True, "Token格式检查通过"

def get_coupon_info(navi_id, activity_name):
    """获取指定活动的优惠券信息"""
    
    # 检查token有效性
    is_valid, msg = check_token_validity(AUTHORIZATION_TOKEN)
    if not is_valid:
        print(f"Token无效: {msg}")
        return None
    
    # 构建完整URL
    url = f"https://gd.brcloud.bankofchina.com/zxyl/coupon/api/wechat/coupon/navi/{navi_id}"
    
    # 复制通用请求头并添加authorization
    headers = COMMON_HEADERS.copy()
    headers["authorization"] = AUTHORIZATION_TOKEN

    try:
        # 发送请求
        print(f"正在获取【{activity_name}】数据...")
        res = requests.get(url, headers=headers, timeout=10)
        
        # 检查HTTP状态码
        if res.status_code != 200:
            print(f"【{activity_name}】请求失败，HTTP状态码: {res.status_code}")
            return None
            
        # 解析JSON响应
        data = res.json()
        print(f"【{activity_name}】请求成功！")
        
        # 检查业务状态
        if data.get('state_code') != 200 or data.get('code') != 'SUCCESS':
            print(f"【{activity_name}】业务请求失败: {data.get('message', '未知错误')}")
            return None
            
        return data
        
    except requests.exceptions.RequestException as e:
        print(f"【{activity_name}】网络请求错误: {e}")
        return None
    except json.JSONDecodeError as e:
        print(f"【{activity_name}】JSON解析错误: {e}")
        print(f"响应内容: {res.text}")
        return None

def parse_coupon_data(data, activity_name):
    """解析优惠券数据"""
    
    if not data or 'body' not in data:
        print(f"【{activity_name}】响应数据格式错误")
        return []
    
    # 检查不同类型的优惠券数据
    coupons = []
    if 'wx_coupon' in data['body'] and data['body']['wx_coupon']:
        coupons = data['body']['wx_coupon']
    elif 'bank_inside_list' in data['body'] and data['body']['bank_inside_list']:
        coupons = data['body']['bank_inside_list']
    elif 'activity_coupon' in data['body'] and data['body']['activity_coupon']:
        coupons = [data['body']['activity_coupon']]  # 如果是单个对象，转为列表
    else:
        print(f"【{activity_name}】未找到优惠券数据")
        return []
    
    parsed_data = []
    
    for coupon in coupons:
        # 解析基本信息 - 处理可能的字段名差异
        coupon_info = {
            'activity_name': activity_name,
            '序号': coupon.get('serial_number', coupon.get('id', '')),
            '名称': coupon.get('stock_name', coupon.get('name', '')),
            '状态': coupon.get('stock_status', coupon.get('status', '')),
            '满减金额': f"{int(coupon.get('transaction_minimum', 0)) / 100}元" if coupon.get('transaction_minimum') else "无门槛",
            '立减金额': f"{int(coupon.get('coupon_amount', 0)) / 100}元",
            '领取条件': coupon.get('description_navi', coupon.get('description', '暂无描述')),
            '用户状态': coupon.get('user_status', ''),
            '领取资格': '有资格' if coupon.get('user_status') == 0 else '无资格',
            '领取开始': coupon.get('receive_begin_time', ''),
            '领取结束': coupon.get('receive_end_time', ''),
            '使用开始': coupon.get('available_begin_time', ''),
            '使用结束': coupon.get('available_end_time', '')
        }
        parsed_data.append(coupon_info)
    
    return parsed_data

def display_all_coupons_table(all_coupons):
    """以表格形式显示所有活动的优惠券信息"""
    
    if not all_coupons:
        print("没有找到任何优惠券数据")
        return ""
    
    table_lines = []
    table_lines.append("=" * 130)
    table_lines.append(f"{'中国银行多活动立减金信息汇总':^130}")
    table_lines.append("=" * 130)
    table_lines.append(f"{'活动':<10} {'名称':<15} {'满减金额':<12} {'立减金额':<10} {'领取资格':<10} {'状态':<10} {'领取条件'}")
    table_lines.append("-" * 130)
    
    for coupon in all_coupons:
        # 简化领取条件显示
        condition = coupon['领取条件']
        if len(condition) > 25:
            condition = condition[:25] + "..."
            
        status_icon = "✅" if coupon['领取资格'] == '有资格' else "❌"
        
        table_lines.append(f"{coupon['activity_name']:<10} {coupon['名称']:<15} {coupon['满减金额']:<12} {coupon['立减金额']:<10} "
              f"{status_icon}{coupon['领取资格']:<8} {coupon['状态']:<10} {condition}")
    
    table_lines.append("=" * 130)
    
    return "\n".join(table_lines)

def display_activity_detail(coupons, activity_name):
    """显示单个活动的详细信息"""
    
    if not coupons:
        print(f"【{activity_name}】没有优惠券数据")
        return ""
    
    detail_lines = []
    detail_lines.append(f"\n" + "=" * 80)
    detail_lines.append(f"【{activity_name}】详细信息")
    detail_lines.append("=" * 80)
    
    for coupon in coupons:
        detail_lines.append(f"\n【{coupon['名称']}】")
        detail_lines.append(f"  • 满减要求: {coupon['满减金额']} 可用 {coupon['立减金额']}")
        detail_lines.append(f"  • 领取资格: {coupon['领取资格']} (用户状态码: {coupon['用户状态']})")
        detail_lines.append(f"  • 活动状态: {coupon['状态']}")
        detail_lines.append(f"  • 领取条件: {coupon['领取条件']}")
        if coupon['领取开始']:
            detail_lines.append(f"  • 领取时间: {coupon['领取开始']} 至 {coupon['领取结束']}")
        if coupon['使用开始']:
            detail_lines.append(f"  • 使用时间: {coupon['使用开始']} 至 {coupon['使用结束']}")
    
    return "\n".join(detail_lines)

def check_user_status_meaning(user_status):
    """解释用户状态码含义"""
    
    status_map = {
        0: "可领取",
        -1: "已领完",
        -2: "活动未开始",
        -3: "活动已结束", 
        -4: "不符合领取条件",
        -5: "已领取过",
        -6: "领取失败",
        -7: "系统错误"
    }
    
    return status_map.get(user_status, f"未知状态({user_status})")

def generate_notify_content(all_coupons):
    """生成通知内容 - 只显示有领取资格的立减金详情"""
    
    if not all_coupons:
        return "未获取到任何优惠券数据，请检查网络连接或token有效性"
    
    # 统计有资格的立减金
    eligible_coupons = [c for c in all_coupons if c['领取资格'] == '有资格']
    ineligible_coupons = [c for c in all_coupons if c['领取资格'] != '有资格']
    
    # 构建通知内容
    content_lines = []
    content_lines.append(f"🎯 {NOTIFY_TITLE} - 查询结果")
    content_lines.append(f"📊 总计: {len(all_coupons)} 个立减金")
    content_lines.append(f"✅ 可领取: {len(eligible_coupons)} 个")
    content_lines.append(f"❌ 无资格: {len(ineligible_coupons)} 个")
    content_lines.append("")
    
    # 只显示有领取资格的立减金详情
    if eligible_coupons:
        content_lines.append("🌟 可领取的立减金详情:")
        for coupon in eligible_coupons:
            # 简化领取条件显示
            condition = coupon['领取条件']
            if len(condition) > 30:
                condition = condition[:30] + "..."
                
            content_lines.append(f"  🏷️ {coupon['activity_name']}-{coupon['名称']}")
            content_lines.append(f"     💰 {coupon['立减金额']} (满{coupon['满减金额']})")
            content_lines.append(f"     📝 {condition}")
            content_lines.append("")  # 空行分隔
    else:
        content_lines.append("😔 暂无可以领取的立减金")
        content_lines.append("")
    
    # 按活动分组统计（只显示统计，不显示无资格的详情）
    content_lines.append("📋 各活动立减金统计:")
    for activity_name in ACTIVITIES.keys():
        activity_coupons = [c for c in all_coupons if c['activity_name'] == activity_name]
        eligible_count = len([c for c in activity_coupons if c['领取资格'] == '有资格'])
        ineligible_count = len(activity_coupons) - eligible_count
        
        if eligible_count > 0:
            # 有可领取的，显示具体数量
            content_lines.append(f"  ✅ {activity_name}: {eligible_count}个可领取")
        else:
            # 没有可领取的，只显示总数
            content_lines.append(f"  ❌ {activity_name}: {len(activity_coupons)}个(无资格)")
    
    return "\n".join(content_lines)

def send_notification(content):
    """发送通知"""
    if HAS_NOTIFY:
        try:
            send(NOTIFY_TITLE, content)
            print("通知发送成功！")
        except Exception as e:
            print(f"通知发送失败: {e}")
    else:
        print("未启用通知功能")

def main():
    """主函数"""
    
    print("中国银行多活动立减金查询工具")
    
    # 检查token有效性
    is_valid, msg = check_token_validity(AUTHORIZATION_TOKEN)
    if not is_valid:
        error_msg = f"Token无效，无法继续: {msg}"
        print(error_msg)
        send_notification(error_msg)
        return
    
    print(f"Token检查通过: {AUTHORIZATION_TOKEN[:50]}...")
    print()
    
    all_coupons = []
    all_details = []
    
    # 遍历所有活动
    for activity_name, activity_config in ACTIVITIES.items():
        navi_id = activity_config["navi_id"]
        
        # 获取活动数据
        data = get_coupon_info(navi_id, activity_name)
        if data:
            # 解析数据
            coupons = parse_coupon_data(data, activity_name)
            if coupons:
                all_coupons.extend(coupons)
                # 显示单个活动详情
                detail = display_activity_detail(coupons, activity_name)
                if detail:
                    all_details.append(detail)
                    print(detail)
        print()
    
    # 显示汇总表格
    if all_coupons:
        table_output = display_all_coupons_table(all_coupons)
        print(table_output)
        
        # 状态码统计
        print("\n" + "=" * 50)
        print("用户状态码统计")
        print("=" * 50)
        status_count = {}
        for coupon in all_coupons:
            status = coupon['用户状态']
            status_count[status] = status_count.get(status, 0) + 1
        
        for status, count in status_count.items():
            meaning = check_user_status_meaning(status)
            print(f"  {status}: {meaning} - {count}个立减金")
        
        # 生成并发送通知
        notify_content = generate_notify_content(all_coupons)
        print("\n" + "=" * 50)
        print("通知内容:")
        print("=" * 50)
        print(notify_content)
        
        send_notification(notify_content)
        
    else:
        error_msg = "未获取到任何优惠券数据，请检查网络连接或token有效性"
        print(error_msg)
        send_notification(error_msg)

def update_authorization(new_token):
    """更新authorization token"""
    global AUTHORIZATION_TOKEN
    AUTHORIZATION_TOKEN = new_token
    print("Authorization token已更新")

if __name__ == "__main__":
    # 如果没有获取到token，提示用户
    if not AUTHORIZATION_TOKEN:
        print("错误: 未找到有效的authorization token")
        print("请在青龙面板中设置环境变量: zy_token")
        print("或者修改代码中的默认token")
        exit(1)
    
    main()